﻿using Mengsk.ProxyDelivery.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows;

namespace Mengsk.ProxyDelivery.Print.Domain.PrintDataFormatters
{
    class PrintDataFormatterManager
    {
        private static List<PrintDataFormatter> formatters = new List<PrintDataFormatter>();

        static PrintDataFormatterManager()
        {
            Type[] types = Assembly.GetExecutingAssembly().GetTypes().Where(obj => obj.BaseType != null && obj.BaseType == typeof(PrintDataFormatter)).ToArray();
            PrintDataFormatter[] temp = types.Select(obj => Activator.CreateInstance(obj) as PrintDataFormatter).ToArray();
            formatters.AddRange(temp);
        }

        public static object Format(PrintTemplate template, PrintTemplateItem templateItem, Order order)
        {
            if (order == null)
            {
                throw new Exception("要格式化的订单参数为空");
            }

            if (templateItem == null)
            {
                throw new Exception("要格式化的格式参数为空");
            }

            PrintDataFormatter formatter = formatters.FirstOrDefault(obj => obj.AcceptType == templateItem.Type);
            if (formatter == null)
            {
                throw new Exception("未能找到格式化算法：" + templateItem.Type + "  " + templateItem.Format);
            }
            try
            {
                return formatter.Format(template, templateItem, order);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace, "格式化数据错误，订单编号:" + order.Id);
                return "";
            }
        }
    }
}
